package com.fzb.forum4j.incp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.apache.struts2.interceptor.ActionMappingParametersInteceptor;

import com.fzb.forum4j.controller.CommonsAction;
import com.fzb.forum4j.po.RequestRecord;
import com.fzb.forum4j.po.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

public class UserInterceptor extends ActionMappingParametersInteceptor{

	/**
	 * 控制不能访问那些方法 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 这个数组的方法未登陆的用户都是无法访问的
	 */
	private static String[] includeMethods;
	
	static{
		includeMethods="go_edit,edit,witer,add,del,update,modify".split(",");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String doIntercept(ActionInvocation invocation) throws Exception {
		long s=System.currentTimeMillis();
		// 从application中的到 accessRecords 
		Map<String, Set<RequestRecord>> map=(Map<String, Set<RequestRecord>>)ServletActionContext.getServletContext().getAttribute("accessRecords");
		// map 中的key 用 月份-时期的方式存储
		SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
		String d=sdf.format(new Date());
		if(map.get(d)==null){
			Set<RequestRecord> requests=new LinkedHashSet<RequestRecord>();
			map.put(d, requests);
		}
		//
		RequestRecord r=new RequestRecord();
		
		//存储用户的访问记录
		r.setAccessTime(new Date());
		r.setParams(invocation.getInvocationContext().getParameters());
		r.setReqeustURl(ServletActionContext.getRequest().getRequestURL());
		r.setRequestIp(ServletActionContext.getRequest().getRemoteAddr());
		r.setUA(ServletActionContext.getRequest().getHeader("User-Agent").substring(0, ServletActionContext.getRequest().getHeader("User-Agent").indexOf(")")+1));
		
		
		if(invocation.getInvocationContext().getSession().get("userMsg")==null)
		{
			//尝试着从 cookie 中得到用户信息用户登陆
			Cookie[] cs=ServletActionContext.getRequest().getCookies();
			if(cs!=null){
				if(invocation.getInvocationContext().getSession().get("userStatus")==null ){
					for(Cookie cookie:cs){
						if(cookie.getName().equals("fid") && invocation.getInvocationContext().getSession().get("autoLogin")==null){
							invocation.getInvocationContext().getSession().put("autoLogin", true);
							//使用 chain跳转来实现自动登陆
							return "doChainLogin";
						}
					}
				}
			}
			for(String str:includeMethods){
				if(invocation.getInvocationContext().getName().equals(str)){
					invocation.getInvocationContext().getSession().put("forward", ((StrutsRequestWrapper)invocation.getInvocationContext().getContextMap().get("com.opensymphony.xwork2.dispatcher.HttpServletRequest")).getRequestURL());
					invocation.getStack().getRoot().clear();
					((StrutsRequestWrapper)invocation.getInvocationContext().getContextMap().get("com.opensymphony.xwork2.dispatcher.HttpServletRequest")).setAttribute("error", "请先登陆");
					r.setUserName("未登陆");
					map.get(d).add(r);
					((Map<String, Set<RequestRecord>>)ServletActionContext.getServletContext().getAttribute("accessRecords")).get(d).add(r);
					return "login";
				}
			}
		}
		else{
			r.setUserName(((User)ActionContext.getContext().getSession().get("userMsg")).getUserName());
			map.get(d).add(r);
		}
		((CommonsAction)ActionContext.getContext().getValueStack().getRoot().get(0)).prepare();
		invocation.getStack().push(((CommonsAction)ActionContext.getContext().getValueStack().getRoot().get(0)).getModel());
		setParameters(invocation.getAction(), invocation.getStack(), invocation.getInvocationContext().getParameters());
		((Map<String, Set<RequestRecord>>)ServletActionContext.getServletContext().getAttribute("accessRecords")).get(d).add(r);
		String str=invocation.invoke();
		
		System.out.println("拦截器耗费了"+(System.currentTimeMillis()-s));
		return str;
	}

}
